package com.sddnytsh.body_buildingsystem.components

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Reply
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.material.icons.filled.ThumbUpOffAlt
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.components.SimpleAvatarImage
import com.sddnytsh.body_buildingsystem.components.DefaultAvatar
import com.sddnytsh.body_buildingsystem.network.CommunityApiService
import com.sddnytsh.body_buildingsystem.topic.Comment
import com.sddnytsh.body_buildingsystem.utils.DateUtils
import kotlinx.coroutines.launch

@Composable
fun CommentWithReplies(
    comment: Comment,
    replies: List<Comment> = emptyList(),
    onCommentLikeUpdate: (Long, Boolean, Int) -> Unit,
    onReplyClick: (Comment) -> Unit,
    onViewMoreReplies: (Long) -> Unit,
    onSendReply: (Long, String) -> Unit
) {
    var showReplyInput by remember { mutableStateOf(false) }
    var replyText by remember { mutableStateOf("") }
    var isSubmittingReply by remember { mutableStateOf(false) }
    val coroutineScope = rememberCoroutineScope()

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White)
            .padding(horizontal = 16.dp, vertical = 8.dp)
    ) {
        // 主评论
        CommentItemWithCallback(
            comment = comment,
            onCommentLikeUpdate = onCommentLikeUpdate,
            onReplyClick = { 
                showReplyInput = !showReplyInput
            }
        )

        // 回复预览区域（300px高度限制）
        if (replies.isNotEmpty()) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 300.dp)
                    .background(
                        Color(0xFFF8F9FA),
                        RoundedCornerShape(8.dp)
                    )
                    .padding(12.dp)
            ) {
                Column {
                    // 回复标题
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "回复 (${replies.size})",
                            style = MaterialTheme.typography.bodyMedium.copy(
                                fontWeight = FontWeight.Medium,
                                color = Color(0xFF666666)
                            )
                        )
                        
                        if (replies.size > 2) {
                            Text(
                                text = "查看更多",
                                modifier = Modifier.clickable {
                                    onViewMoreReplies(comment.id)
                                },
                                style = MaterialTheme.typography.bodySmall.copy(
                                    color = Color(0xFF4361EE),
                                    fontWeight = FontWeight.Medium
                                )
                            )
                        }
                    }

                    Spacer(modifier = Modifier.height(8.dp))

                    // 显示最新2条回复
                    val displayReplies = replies.take(2)
                    displayReplies.forEach { reply ->
                        ReplyItem(
                            reply = reply,
                            onReplyLikeUpdate = { replyId, isLiked, likeCount ->
                                // 更新回复的点赞状态
                                onCommentLikeUpdate(replyId, isLiked, likeCount)
                            }
                        )
                        if (reply != displayReplies.last()) {
                            Spacer(modifier = Modifier.height(4.dp))
                        }
                    }
                }
            }
        }

        // 回复输入框
        if (showReplyInput) {
            Spacer(modifier = Modifier.height(8.dp))
            ReplyInputSection(
                replyText = replyText,
                onReplyChange = { replyText = it },
                isSubmitting = isSubmittingReply,
                onSendReply = {
                    if (replyText.trim().isNotEmpty()) {
                        coroutineScope.launch {
                            isSubmittingReply = true
                            try {
                                onSendReply(comment.id, replyText.trim())
                                replyText = ""
                                showReplyInput = false
                            } catch (e: Exception) {
                                // 处理错误
                            } finally {
                                isSubmittingReply = false
                            }
                        }
                    }
                },
                onCancel = {
                    showReplyInput = false
                    replyText = ""
                }
            )
        }
    }
}

@Composable
fun ReplyItem(
    reply: Comment,
    onReplyLikeUpdate: (Long, Boolean, Int) -> Unit
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.Top
    ) {
        // 用户头像
        if (reply.authorAvatar != null) {
            SimpleAvatarImage(
                avatarUrl = reply.authorAvatar,
                fallbackName = reply.author ?: "用户",
                size = 24.dp
            )
        } else {
            DefaultAvatar(
                name = reply.author ?: "用户",
                size = 24.dp
            )
        }

        Spacer(modifier = Modifier.width(8.dp))

        // 回复内容
        Column(
            modifier = Modifier.weight(1f)
        ) {
            // 用户名和时间
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = reply.author ?: "用户${reply.userId}",
                    style = MaterialTheme.typography.bodySmall.copy(
                        fontWeight = FontWeight.Medium,
                        color = Color(0xFF333333)
                    )
                )
                
                Spacer(modifier = Modifier.width(8.dp))
                
                Text(
                    text = DateUtils.formatDate(reply.createdAt),
                    style = MaterialTheme.typography.bodySmall.copy(
                        color = Color(0xFF999999)
                    )
                )
            }

            Spacer(modifier = Modifier.height(2.dp))

            // 回复内容
            Text(
                text = reply.content,
                style = MaterialTheme.typography.bodySmall.copy(
                    color = Color(0xFF333333)
                ),
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )

            Spacer(modifier = Modifier.height(4.dp))

            // 点赞按钮
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(
                    onClick = {
                        onReplyLikeUpdate(reply.id, !reply.isLiked, reply.likeCount)
                    },
                    modifier = Modifier.size(20.dp)
                ) {
                    Icon(
                        imageVector = if (reply.isLiked) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
                        contentDescription = "点赞",
                        tint = if (reply.isLiked) Color(0xFFE91E63) else Color(0xFF999999),
                        modifier = Modifier.size(16.dp)
                    )
                }
                
                Text(
                    text = reply.likeCount.toString(),
                    style = MaterialTheme.typography.bodySmall.copy(
                        color = Color(0xFF999999)
                    )
                )
            }
        }
    }
}

@Composable
fun ReplyInputSection(
    replyText: String,
    onReplyChange: (String) -> Unit,
    isSubmitting: Boolean,
    onSendReply: () -> Unit,
    onCancel: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(
                Color(0xFFF8F9FA),
                RoundedCornerShape(8.dp)
            )
            .padding(12.dp)
    ) {
        // 输入框
        OutlinedTextField(
            value = replyText,
            onValueChange = onReplyChange,
            placeholder = { Text("回复...") },
            modifier = Modifier.fillMaxWidth(),
            maxLines = 3,
            colors = OutlinedTextFieldDefaults.colors(
                focusedBorderColor = Color(0xFF4361EE),
                unfocusedBorderColor = Color(0xFFE0E0E0)
            )
        )

        Spacer(modifier = Modifier.height(8.dp))

        // 按钮
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.End
        ) {
            TextButton(onClick = onCancel) {
                Text("取消", color = Color(0xFF666666))
            }
            
            Spacer(modifier = Modifier.width(8.dp))
            
            Button(
                onClick = onSendReply,
                enabled = replyText.trim().isNotEmpty() && !isSubmitting,
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFF4361EE)
                )
            ) {
                if (isSubmitting) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(16.dp),
                        strokeWidth = 2.dp,
                        color = Color.White
                    )
                } else {
                    Text("发送", color = Color.White)
                }
            }
        }
    }
}

@Composable
fun CommentItemWithCallback(
    comment: Comment,
    onCommentLikeUpdate: (Long, Boolean, Int) -> Unit = { _, _, _ -> },
    onReplyClick: (Comment) -> Unit = {}
) {
    // 评论点赞状态
    var isLiked by remember { mutableStateOf(comment.isLiked) }
    var likeCount by remember { mutableStateOf(comment.likeCount) }
    val coroutineScope = rememberCoroutineScope()
    val communityApiService = remember { CommunityApiService() }
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 4.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
    ) {
        Column(
            modifier = Modifier.padding(12.dp)
        ) {
            // 用户信息
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth()
            ) {
                // 头像
                if (comment.authorAvatar != null) {
                    SimpleAvatarImage(
                        avatarUrl = comment.authorAvatar,
                        fallbackName = comment.author ?: "用户",
                        size = 32.dp
                    )
                } else {
                    DefaultAvatar(
                        name = comment.author ?: "用户",
                        size = 32.dp
                    )
                }
                
                Spacer(modifier = Modifier.width(8.dp))
                
                // 用户名和时间
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = comment.author ?: "匿名用户",
                        style = MaterialTheme.typography.bodySmall.copy(fontWeight = FontWeight.SemiBold),
                        color = Color(0xFF333333)
                    )
                    Text(
                        text = DateUtils.formatDate(comment.createdAt),
                        style = MaterialTheme.typography.bodySmall,
                        color = Color.Gray,
                        fontSize = 10.sp
                    )
                }
                
                // 操作按钮区域
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    // 点赞按钮
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.clickable {
                            val currentUserId = UserState.currentUserId
                            if (currentUserId != null) {
                                coroutineScope.launch {
                                    try {
                                        val result = communityApiService.toggleCommentLike(currentUserId, comment.id)
                                        if (result.isSuccess) {
                                            isLiked = !isLiked
                                            likeCount = if (isLiked) likeCount + 1 else likeCount - 1
                                            onCommentLikeUpdate(comment.id, isLiked, likeCount)
                                        }
                                    } catch (e: Exception) {
                                        // 处理错误
                                    }
                                }
                            }
                        }
                    ) {
                        Icon(
                            imageVector = if (isLiked) Icons.Default.ThumbUp else Icons.Default.ThumbUpOffAlt,
                            contentDescription = "点赞",
                            tint = if (isLiked) Color(0xFFE91E63) else Color.Gray,
                            modifier = Modifier.size(16.dp)
                        )
                        Spacer(modifier = Modifier.width(2.dp))
                        Text(
                            text = likeCount.toString(),
                            style = MaterialTheme.typography.bodySmall,
                            color = if (isLiked) Color(0xFFE91E63) else Color.Gray,
                            fontSize = 10.sp
                        )
                    }
                    
                    // 回复按钮
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.clickable {
                            onReplyClick(comment)
                        }
                    ) {
                        Icon(
                            imageVector = Icons.Default.Reply,
                            contentDescription = "回复",
                            tint = Color(0xFF4361EE),
                            modifier = Modifier.size(16.dp)
                        )
                        Spacer(modifier = Modifier.width(2.dp))
                        Text(
                            text = "回复",
                            style = MaterialTheme.typography.bodySmall,
                            color = Color(0xFF4361EE),
                            fontSize = 10.sp
                        )
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 评论内容
            Text(
                text = comment.content,
                style = MaterialTheme.typography.bodyMedium,
                color = Color(0xFF555555),
                lineHeight = 18.sp,
                modifier = Modifier.fillMaxWidth()
            )
        }
    }
}
